package com.zp.datax.core;


import com.zp.datax.core.model.DataxJobTrigger;
import com.zp.datax.core.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 开始时间条件处理器
 *
 * @author bruce
 * @date 2019-07-15
 */
@Slf4j
public class StartTimeCondition extends Condition {

    public StartTimeCondition() {
        super();
    }

    public StartTimeCondition(DataxJobTrigger dataxJobTrigger) {
        super(dataxJobTrigger);
    }

    public StartTimeCondition(Condition condition) {
        super(condition);
    }

    public StartTimeCondition(Condition condition, DataxJobTrigger dataxJobTrigger) {
        super(condition);
    }

    @Override
    public Object[] append(String str) {

        Object[] objarray = getObjarray(str);

        DataxJobTrigger dataxJobTrigger = getDataxJobTrigger();
        String condition = Objects.toString(objarray[0]);
        Long currentTimeMillis = Long.valueOf(Objects.toString(objarray[1]));

        Integer range = dataxJobTrigger.getRange();
        Integer unit = dataxJobTrigger.getUnit();

        Long bizStarTime = dataxJobTrigger.getBizStarTime();
        Long bizEndTime = dataxJobTrigger.getBizEndTime();

        Long startTime;
        if (range.compareTo(0) == -1
                && unit.compareTo(0) == 1
                && unit.compareTo(7) == -1
                && str.contains("endTime")) {
            startTime = ConditionUnit.plus(currentTimeMillis, Long.valueOf(range), unit);
        } else {
            if (!str.contains("startTime")) {
                return objarray;
            }
            if (bizStarTime.compareTo(0L) == 0
                    && bizEndTime.compareTo(0L) == 0) {//初次自动执行，按当前时间开始执行
                startTime = currentTimeMillis;
            } else if (bizEndTime.compareTo(0L) == 1
                    && bizStarTime.compareTo(0L) == 1
                    && bizEndTime.compareTo(bizStarTime) == 1) {
                startTime = bizEndTime;
            } else {
                String message = String.format(
                        "同步失败 :: taskId :: %s, 根据分析本次同步的参数startTime起始时间值无法确定，可能原因分析：\n1、参数名与同步范围组合错误；\n2、上次同步异常；\n建议手动指定参数值进行同步；"
                        , dataxJobTrigger.getTaskId());
                log.error(message);
                log.info("dataxJobTrigger :: {}", dataxJobTrigger);
                throw new IllegalArgumentException(message);
            }
        }

        objarray[0] = String.format("%sstartTime=%s,", condition, TimeUtil.parserT(startTime));
        dataxJobTrigger.setBizStarTime(startTime);

        return objarray;

    }

}
